/**
 * Copyright(c) 2014 Xunton Solutions
 *
 * History:
 *   15-1-10 下午4:21 Created by dwzhang
 */
package com.jade.modules.region.impl;

import java.util.List;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.jade.framework.base.criterion.Criteria;
import com.jade.framework.base.criterion.sql.SqlUtils;
import com.jade.framework.base.util.PagingList;
import com.jade.modules.region.Region;
import com.jade.modules.region.RegionDao;
import com.jade.modules.region.RegionException;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;

/**
 * 采用JPA方式进行存储的数据访问接口。
 *
 * @author sky
 * @version 1.0 13-4-23 上午11:46
 */
@Named ("module_regionDao")
public class JpaRegionDao
        implements RegionDao
{
    @PersistenceContext (unitName = "default")
    protected EntityManager em;

    @Caching (evict = {@CacheEvict (value = "module.region.g", key = "#region.id"),
            @CacheEvict (value = "module.region.l", allEntries = true),
            @CacheEvict (value = "module.region.q", allEntries = true)})
    public void addRegion(Region region)
            throws RegionException
    {
        em.persist(region);
    }

    @Caching (evict = {@CacheEvict (value = "module.region.g", key = "#region.id"),
            @CacheEvict (value = "module.region.l", allEntries = true),
            @CacheEvict (value = "module.region.q", allEntries = true)})
    public void updateRegion(Region region)
            throws RegionException
    {
        em.merge(region);
    }

    @Cacheable (value = "module.region.g", key = "#id")
    public Region getRegion(String id)
    {
        return em.find(Region.class, id);
    }

    @Caching (evict = {@CacheEvict (value = "module.region.g", key = "#region.id"),
            @CacheEvict (value = "module.region.l", allEntries = true),
            @CacheEvict (value = "module.region.q", allEntries = true)})
    public void removeRegion(Region region)
            throws RegionException
    {
        region = em.find(Region.class, region.getId());
        em.remove(region);
    }

    @Cacheable (value = "module.region.l", key = "#criteria.toString()")
    public List<Region> listRegion(Criteria criteria)
    {
        return SqlUtils.sqlQueryWithoutCount(SQL_REGION, em, criteria);
    }

    @Cacheable (value = "module.region.q", key = "#criteria.toString()")
    public PagingList<Region> queryRegion(Criteria criteria)
    {
        return SqlUtils.sqlQuery(SQL_REGION, em, criteria);
    }

    protected static final String SQL_REGION = "SELECT region FROM com.jade.modules.region.Region region";
}
